﻿using UnityEngine;

public class FPS : MonoBehaviour {
	// === Unity ======================================================================================================
	public UILabel Label;
	
	private void Start() {
		if (!Label) {
			Debug.Log("FramesPerSecond needs a UILabel component!");
			enabled = false;
			return;
		}
		_timeleft = UPDATE_INTERVAL;
	}

	private void Update() {
		_timeleft -= Time.deltaTime;
		_accum += Time.timeScale / Time.deltaTime;
		_frames++;

		if (!(_timeleft <= 0.0f)) {
			return;
		}
		var fps = _accum / _frames;
		var format = System.String.Format("{0:F2}", fps);
		Label.text = format;

		if (fps > 50f) {
			Label.color = Color.green;
		} else if (fps > 30f) {
			Label.color = Color.yellow;
		} else if (fps > 10f) {
			Label.color = Color.magenta;
		} else {
			Label.color = Color.red;
		}


		_timeleft = UPDATE_INTERVAL;
		_accum = 0.0f;
		_frames = 0;
	}

	// === Private ====================================================================================================
	private const float UPDATE_INTERVAL = 0.5f;
	private int _frames;
	private float _accum;
	private float _timeleft;
}